package cn.lcfms.app.weixin.util;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import cn.lcfms.app.weixin.service.WxApiService;
import cn.lcfms.app.weixin.support.AesException;
import cn.lcfms.app.weixin.support.WXBizMsgCrypt;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

public class WeixinDecrypMsg {
	private static Logger logger = Logger.getLogger(WeixinDecrypMsg.class); 
	/**
	 * 获取xml消息解密并返回值
	 */
	public static JSONObject decryptMsg(WxApiService ws,String msgSignature, String timeStamp, String nonce, String xml) {
		JSONObject json=new JSONObject();
		try {
			WXBizMsgCrypt wx=new WXBizMsgCrypt(ws.getToken(), ws.getEncodingAESKey(), ws.getAppid());
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			StringReader sr = new StringReader(xml);
			InputSource is = new InputSource(sr);
			Document document = db.parse(is);
			Element root = document.getDocumentElement();
			NodeList nodelist = root.getElementsByTagName("Encrypt");			
			String encrypt = nodelist.item(0).getTextContent();
			String format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%1$s]]></Encrypt></xml>";
			String fromXML = String.format(format, encrypt);
			String result = wx.decryptMsg(msgSignature, timeStamp, nonce, fromXML);
			logger.info("微信解密消息：\n"+result);
			XMLSerializer xmlSerializer = new XMLSerializer();
			json = (JSONObject) xmlSerializer.read(result);			
		} catch (AesException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return json;
	}	
}
